package com.example.scanidcard;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;
import java.io.File;
import java.nio.file.Files;

// 结果页面，显示身份证识别后的结果信息
public class ResultActivity extends AppCompatActivity {

    private TextView resultTextView;
    private TextView backResultTextView;
    private Button backButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);

        resultTextView = findViewById(R.id.resultTextView);
        backResultTextView = findViewById(R.id.backResultTextView);
        backButton = findViewById(R.id.backButton);

        // 设置按钮点击事件用于返回主页面
        backButton.setOnClickListener(v -> {
            Intent intent = new Intent(ResultActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        });

        // 获取传递的图片路径
        String frontImagePath = getIntent().getStringExtra("frontImagePath");
        String backImagePath = getIntent().getStringExtra("backImagePath");

        // OCR识别分别处理正面和反面图片
        if (frontImagePath != null && backImagePath != null) {
            sendOcrRequest(frontImagePath, "正面");
            sendOcrRequest(backImagePath, "反面");
        } else {
            Toast.makeText(this, "未接收到图片数据", Toast.LENGTH_SHORT).show();
            finish();
        }
    }


    // 发送OCR请求到腾讯云服务
    private void sendOcrRequest(String imagePath, String side) {
        new Thread(() -> {
            try {
                // 图片文件转换为Base64字符串
                File imageFile = new File(imagePath);
                String imageBase64 = Base64Util.encodeBase64(Files.readAllBytes(imageFile.toPath()));

                String requestBody = new JSONObject()
                        .put("ImageBase64", imageBase64) // 添加图片数据
                        .toString();

                // 我的腾讯云API的密钥，这里隐藏
                String secretId = "";
                String secretKey = "";
                // 发送请求获取返回结果
                String response = TecentHttpUtil.sendRequest(secretId, secretKey, requestBody);
                // 在主线程更新UI，处理返回结果
                runOnUiThread(() -> handleOcrResponse(response, side));
            } catch (Exception e) {
                e.printStackTrace();
                runOnUiThread(() -> Toast.makeText(ResultActivity.this, "请求失败：" + e.getMessage(), Toast.LENGTH_SHORT).show());
            }
        }).start();
    }

    // 处理OCR服务返回的响应数据
    private void handleOcrResponse(String response, String side) {
        try {
            JSONObject jsonResponse = new JSONObject(response);
            if (jsonResponse.has("Response")) {
                JSONObject responseData = jsonResponse.getJSONObject("Response");

                if (side.equals("正面")) {
                    // 提取正面信息
                    String idName = responseData.optString("Name", "未知姓名");
                    String gender = responseData.optString("Sex", "未识别性别");
                    String ethnicity = responseData.optString("Nation", "未识别民族");
                    String birthDate = responseData.optString("Birth", "未识别出生日期");
                    String address = responseData.optString("Address", "未知住址");
                    String idNumber = responseData.optString("IdNum", "未知身份证号");

                    // 更新正面结果显示
                    resultTextView.setText("正面结果：\n姓名：" + idName +
                            "\n性别：" + gender + "\n民族：" + ethnicity +
                            "\n出生：" + birthDate + "\n住址：" + address +
                            "\n公民身份号码：" + idNumber + "\n\n");
                } else if (side.equals("反面")) {
                    // 提取反面信息
                    String issuingAuthority = responseData.optString("Authority", "未识别签发机关");
                    String validDate = responseData.optString("ValidDate", "未识别有效期限");

                    // 更新反面结果显示
                    backResultTextView.setText("反面结果：\n签发机关：" + issuingAuthority +
                            "\n有效期限：" + validDate + "\n\n");
                }
            } else {
                resultTextView.append(side + "解析失败：" + jsonResponse.toString() + "\n\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultTextView.append(side + "解析失败：" + e.getMessage() + "\n\n");
        }
    }
}
